package app.musicPlayer.domain;

import java.util.ArrayList;



import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import app.persistencia.ListaDeReproduccion;
import app.persistencia.ListasDeReproduccion;
import app.utils.Utiles;

public class ViewLists extends ListActivity {
	    
		Integer idListSelected;
		ArrayAdapter<ListaDeReproduccion> adapter;
		ArrayList<ListaDeReproduccion> arrayListas;
		public void onCreate(Bundle icicle) {
			super.onCreate(icicle);
			ListasDeReproduccion listas = ListasDeReproduccion.getIntances();
			arrayListas = listas.getList();
			// Create an array of Strings, that will be put to our ListActivity
			adapter = new InteractiveArrayAdapterListasReproduccion(this,arrayListas);
			setListAdapter(adapter);
			final ListView listsview = getListView();
			listsview.setOnItemClickListener(new OnItemClickListener() {
	            public void onItemClick(AdapterView<?> parent, View v, int posicion, long id) {
        			idListSelected = arrayListas.get(posicion).getId();
        			goViewSongLista();
	            }
	        });
			listsview.setOnItemLongClickListener(new OnItemLongClickListener() {
	            
	            public boolean onItemLongClick(AdapterView<?>
	            		parent, View v, int posicion, long id) {
	            	idListSelected = arrayListas.get(posicion).getId();
        			registerForContextMenu(listsview);
					return false;
	            }
	        });
		}

		@Override  
		public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
	    	super.onCreateContextMenu(menu, v, menuInfo);
			menu.setHeaderTitle("Menu Lista");  
			menu.add(0, v.getId(), 0, "Reproducir");
			menu.add(0, v.getId(), 0, "Ver");
			menu.add(0, v.getId(),0, "Editar Lista");
			menu.add(0, v.getId(),0, "Borrar");
		}
		
	    @Override  
		public boolean onContextItemSelected(MenuItem item) {  
	    	if(item.getTitle()=="Ver"){
	    		goViewSongLista();
	    	}  
	    	else if(item.getTitle()=="Borrar"){
	    		borrar();
	    	}
	    	else if(item.getTitle()=="Reproducir"){
	    		goReproducir();
	    	}
	    	else if(item.getTitle()=="Editar Lista") {
	    		goSongsByListSelection();
	    	}
	    	else {return false;}  
	    	return true;  
	    }
		private void goSongsByListSelection() {
			if(ListasDeReproduccion.getIntances().getListaDeReproduccion(idListSelected).isEmpty()) {
				Utiles.showMessage(ViewLists.this, "Lista de reproduccion vacia");
				return;
			}
			Intent intent = new Intent(ViewLists.this,SongsByListSelection.class);
			Bundle b = new Bundle();
			b.putString("ID", String.valueOf(idListSelected));
			intent.putExtras(b);
			finish();
			startActivity(intent);
		}

		protected void goViewSongLista() {
			if(ListasDeReproduccion.getIntances().getListaDeReproduccion(idListSelected).isEmpty()) {
				Utiles.showMessage(ViewLists.this, "Lista de reproduccion vacia");
				return;
			}
			Intent intent = new Intent(ViewLists.this,ViewSongByList.class);
			Bundle b = new Bundle();
			b.putString("ID", String.valueOf(idListSelected));
			intent.putExtras(b);
			finish();
			startActivity(intent);
		}
		private void goReproducir() {
			if(ListasDeReproduccion.getIntances().getListaDeReproduccion(idListSelected).isEmpty()) {
				Utiles.showMessage(ViewLists.this, "Lista de reproduccion vacia");
				return;
			}
			ReproduccionActual.getIntances().assignNewSongsList(
					ListasDeReproduccion.getIntances().
					getListaDeReproduccion(idListSelected).getListaRep());
		 	Intent intent = new Intent(ViewLists.this, Mp3player.class);
	    	finish();
	    	startActivity(intent);
		}
		private void borrar() {
			AlertDialog alertDialog = new AlertDialog.Builder(ViewLists.this).create();
	    	alertDialog.setTitle("Borrar");
			alertDialog.setMessage("¿Estas seguro que deseas borrar la lista de reproduccion?");
	 	    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
	    	      public void onClick(DialogInterface dialog, int which) {
	    	 
	    	    	ListasDeReproduccion.getIntances().deleteLista(ViewLists.this, idListSelected);
	    	    	Utiles.showMessage(ViewLists.this, "Se ha borrado con exito");
	    			returnToViewList(null);
	    	    } });
	     	 alertDialog.setButton2("CANCEL", new DialogInterface.OnClickListener() {
	   	      public void onClick(DialogInterface dialog, int which) {
	   	    	  
	   	    } });
	     	alertDialog.show();
		}
		private void returnToViewList(Bundle b) {
	    	Intent intent = new Intent(ViewLists.this, ViewLists.class);
	    	if(b != null) {
	    		intent.putExtras(b);
	    	}
	    	finish();
	    	startActivity(intent);
		}
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
		    MenuInflater inflater = getMenuInflater();
		    inflater.inflate(R.menu.viewlistmenu, menu);
		    return true;
		}
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
		    switch (item.getItemId()) {
		        case R.id.crear:
		        	create();
		        	return true;
		        case R.id.borrarN:
		            seleccion();
		            return true;
		        case R.id.Volver :
		        	returnToViewMain(null);
		        	return true;
		       default :
		            return super.onOptionsItemSelected(item);
		    }
		}

		private void returnToViewMain(Object object) {
	    	Intent intent = new Intent(ViewLists.this, SocialMusicPlayerActivity.class);
	    	finish();
	    	startActivity(intent);
		}

		private void seleccion() {
			Intent intent = new Intent(ViewLists.this, ListsSelection.class);
	    	finish();
	    	startActivity(intent);
		}

		private void create() {
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(ViewLists.this);
			final EditText input = new EditText(ViewLists.this);
			alertDialog.setTitle("Crear Lista");
			alertDialog.setMessage("Inseta el nombre de la lista");
			alertDialog.setView(input);
	 	    alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	    	      public void onClick(DialogInterface dialog, int which) {
	    	    	String text = input.getText().toString().trim();
	    	    	if(text.length() > 0) { 
	    	    		if(ListasDeReproduccion.getIntances().existListWithName(ViewLists.this, text)) {
	    	    			Utiles.showMessage(ViewLists.this, "Nombre de lista de reproduccion ya existente");
	    	    		}
	    	    		ListasDeReproduccion.getIntances().addNewLista(ViewLists.this,text);
    	    			Utiles.showMessage(ViewLists.this, "Nueva lista de reproduccion creada con exito");
	    	    		returnToViewList(null);
	    	    	}
	    	    	else
	    	    		Utiles.showMessage(ViewLists.this, "El campo de texto esta vacio");
	    	    } });
	     	  alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
	   	      public void onClick(DialogInterface dialog, int which) {
	   	    	  
	   	    } });
	     	alertDialog.show();
	    }
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
	        if (keyCode == KeyEvent.KEYCODE_BACK) {
	            //moveTaskToBack(true);          
	            returnToViewMain(null);
	            return true;
	        }
	        return super.onKeyDown(keyCode, event);
	    }

}
